Shader "post/godRay"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Bloom ("Bloom", 2D) = "black" {}
        _LuminanceThreshold ("Luminance Threshold", Float) = 0.5
    }

    SubShader{
        CGINCLUDE

        #include "UnityCG.cginc"

        sampler2D _MainTex;
        half4 _MainTex_TexelSize;
        sampler2D _GodRay;
        float _LuminanceThreshold;
        float2 _blurCenter;
        float _blurFactor;
        int _blurNum;
        float _lightFactor;


        struct v2f {
            float4 pos : SV_POSITION;
            half2 uv :TEXCOORD0;
        };

        v2f vertExtractBright(appdata_img v){
            v2f o;

            o.pos = UnityObjectToClipPos(v.vertex);

            o.uv = v.texcoord;

            return o;
        }

        fixed luminance(fixed4 color){
            return 0.2125 * color.r + 0.7154 * color.g + 0.0721 * color.b;
        }

        fixed4 fragExtractBright(v2f i) : SV_Target {
            fixed4 c = tex2D(_MainTex, i.uv);
            fixed val = clamp( luminance(c)- _LuminanceThreshold , 0.0, 1.0);

            return c * val;
        }

        struct v2fVert { 
			float4 pos : SV_POSITION;
			half2 uv: TEXCOORD0;
		};
	
		
		v2fVert vertRayBlur(appdata_img v) {
			v2fVert o;
			o.pos = UnityObjectToClipPos(v.vertex);
			o.uv = v.texcoord;
			 
			return o;
		}
		
		fixed4 fragRayBlur(v2fVert i) : SV_Target {
            fixed4 color = fixed4(0,0,0,0);

			for (int j = 1; j <= _blurNum; j++) {
                float2 dir = i.uv - _blurCenter;
                color += tex2D(_MainTex, i.uv - _blurFactor * dir * j);
			}
			
            color /= _blurNum;
			return color;
		}


        struct v2fBloom {
            float4 pos : SV_POSITION;
            half4 uv : TEXCOORD0;
        };

        v2fBloom vertComposite(appdata_img v){
            v2fBloom o;
            o.pos = UnityObjectToClipPos(v.vertex);
            o.uv.xy = v.texcoord;
            o.uv.zw = v.texcoord;

            #if UNITY_UV_STARTS_AT_TOP
            if (_MainTex_TexelSize.y < 0.0)
                o.uv.w =  1.0 - o.uv.w;
            #endif

            return o;
        }

        fixed4 fragComposite(v2fBloom i) : SV_Target{
            return tex2D(_MainTex, i.uv.xy) + _lightFactor * tex2D(_GodRay, i.uv.zw);
        }

        ENDCG

        ZTest Always Cull Off ZWrite Off

        Pass{
            
			CGPROGRAM  
			#pragma vertex vertExtractBright  
			#pragma fragment fragExtractBright  
			
			ENDCG  
        }

        Pass{
            CGPROGRAM
            #pragma vertex vertRayBlur
            #pragma fragment fragRayBlur

            ENDCG
        }

        Pass {
            CGPROGRAM
            #pragma vertex vertComposite
            #pragma fragment fragComposite

            ENDCG
        }

    }
    // FallBack Off
}
